// pages/addbook/addbook.js
var util = require('../../utils/util.js')
const DB = wx.cloud.database()
//获取应用实例
const app = getApp()
const userinfo = wx.getStorageSync('userinfo')



Page({
  /**
   * 页面的初始数据
   */
  data: {
    //处理导 航 栏的高度
    rpxdata: wx.getStorageSync('rpxdata'),
    navigationBarAndStatusBarHeight: wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight') + 'px',
    navigationBarAndStatusBarAndsearchHeight: wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight') + 60 + 'px',
    //设置导航栏的显示信息
    navbarData: {
      showCapsule: 1,
      title: "书籍管理"
    },
    //处理用户信息
    openid: 0,
    manger: 0,
    //处理按键颜色
    btn_js: 0,
    btn_hs: 0,
    //统计信息
    outbook: 0,
    inbook:  0,
    hsbook: 0,
    //pickerlist
    picker_list: ["其它", "质量", "内分泌", "5S~7S", "基础护理", "教学", "文学", "管理", "英文"],
    //输入书的属性字段
    bookinfo: {
      bookname: "",
      bookclass: "其它",
      isbn: "",
      author: "",
      uptime: "",
      update: "",
      bookpic: "cloud://xuwei-lch1-7.7875-xuwei-lch1-7-1303119743/懒小丫借书/默认图片.jpg",
      stock: 1,
      jynum: 0,
      pubdata: "",
      publisher: "",
      summary: "",
      images_medium: "",
      images_large: "",
      isbn10: "",
      jystate: false

    }

  },

  //手动输入
  manual_input: function () {
    let that = this
    this.setData({
      btn_js: 1
    })
    if (this.data.manger == 0) {
      wx.showToast({
        title: '需要管理员',
        image: '/images/fail.png',
        duration: 2000
      })
    } else {
      if (that.data.bookinfo.bookname == '') {
        wx.showToast({
          title: '请输入书名',
          image: '/images/fail.png',
          duration: 2000
        })
      } else {
        DB.collection("lchbook").where({
          isbn: that.data.bookinfo.isbn
        }).get({
          success(res) {
            let id = res.data[0]
            if (id == undefined) {
              DB.collection("lchbook").add({
                data: that.data.bookinfo,
                success: function (res) {
                  wx.showToast({
                    title: '添加成功',
                    icon: 'success',
                    duration: 2000
                  })
                },
                fail: function (res) {
                  wx.showToast({
                    title: '添加失败',
                    image: '/images/fail.png',
                    duration: 2000
                  })
                }
              })
            } else {
              wx.showToast({
                title: 'ISBN已经存在',
                image: '/images/fail.png',
                duration: 2000
              })
            }
          }
        })
      }
    }

  },
  //扫描输入
  shaoma_input() {
    this.setData({
      btn_hs: 1
    })
    let that = this
    if (this.data.manger == 0) {
      wx.showToast({
        title: '需要管理员',
        image: '/images/fail.png',
        duration: 2000
      })
      that.setData({
        btn_hs: 0
      })
    } else if (this.data.bookinfo.bookname == "") {
      wx.showToast({
        title: '请输入书名',
        image: '/images/fail.png',
        duration: 2000
      })
      that.setData({
        btn_hs: 0
      })
    } else if (this.data.bookinfo.isbn == "") {
      wx.showToast({
        title: '请输入ISBN',
        image: '/images/fail.png',
        duration: 2000
      })
      that.setData({
        btn_hs: 0
      })
    } else {
      DB.collection("lchbook").where({
        isbn: that.data.bookinfo.isbn
      }).get({
        success(res) {
          let id = res.data[0]
          if (id == undefined) {
            DB.collection("lchbook").add({
              data: that.data.bookinfo,
              success: function (res) {
                wx.showToast({
                  title: '添加成功',
                  icon: 'success',
                  duration: 2000
                })
                that.setData({
                  btn_hs: 0
                })
              },
              fail: function (res) {
                wx.showToast({
                  title: '添加失败',
                  image: '/images/fail.png',
                  duration: 2000
                })
                that.setData({
                  btn_hs: 0
                })
              }
            })
          } else {
            wx.showToast({
              title: 'ISBN已经存在',
              image: '/images/fail.png',
              duration: 2000
            })
            that.setData({
              btn_hs: 0
            })
          }
        }
      })
    }


  },

  //存储图片
  storage_pic() {
    let that = this
    wx.chooseImage({
      count: 1,
      success(res) {

        wx.cloud.uploadFile({
          filePath: res.tempFilePaths[0],
          cloudPath: "懒小丫借书/" + that.data.bookinfo.bookname,
          success(e) {
            let val = that.data.bookinfo
            that.data.bookinfo.bookpic = e.fileID
            that.setData({
              bookinfo: val
            })
          },
          fail(e) {
            wx.showToast({
              title: '图片上传失败!',
              image: '/images/fail.png',
              duration: 2000
            })
          }
        })
      }
    })
  },

  //扫码信息
  shaoma() {
    let that = this
    wx.scanCode({
      onlyFromCamera: false,
      success: (res) => {
        console.log("scan", res)
        let val = that.data.bookinfo
        that.data.bookinfo.isbn = res.result
        var apiUrl = "https://isbn.market.alicloudapi.com/ISBN?isbn=" + res.result
        console.log("url", apiUrl)
        wx.request({
          url: apiUrl,
          method: 'GET',
          header: {
            'content-type': 'application/json',
            'Authorization': 'APPCODE ' + '11378d713f064597a2759f2ac0728606'
          },
          success(res) {
            console.log(res.data)
            that.data.bookinfo.author = res.data.result.author
            that.data.bookinfo.pubdata = res.data.result.pubdata
            that.data.bookinfo.bookname = res.data.result.title
            that.data.bookinfo.publisher = res.data.result.publisher
            that.data.bookinfo.summary = res.data.result.summary
            that.data.bookinfo.images_medium = res.data.result.images_medium
            that.data.bookinfo.images_large = res.data.result.images_large
            that.data.bookinfo.isbn10 = res.data.result.isbn10
            that.data.bookinfo.uptime = util.formatTime(new Date())
            that.data.bookinfo.update = util.formatDate(new Date())
            that.setData({
              bookinfo: val
            })
          }

        })
      },
      fail: (res) => {
        console.log("fail", res)
        wx.showToast({
          title: '扫描失败手动录入',
          image: '/images/fail.png',
          duration: 2000
        })
      }
    })

  },



  //选择书的类别
  bindChange: function (e) {
    let val = this.data.bookinfo
    this.data.bookinfo.bookclass = this.data.picker_list[e.detail.value]
    this.setData({
      bookinfo: val
    })
  },
  //接收输入信息
  input_bookname(e) {
    let val = this.data.bookinfo
    this.data.bookinfo.bookname = e.detail.value
    this.data.bookinfo.uptime = util.formatTime(new Date())
    this.data.bookinfo.update = util.formatDate(new Date())
    this.setData({
      bookinfo: val
    })
  },
  input_ISBN(e) {
    let val = this.data.bookinfo
    this.data.bookinfo.isbn = e.detail.value
    this.setData({
      bookinfo: val
    })
  },
  input_author(e) {
    let val = this.data.bookinfo
    this.data.bookinfo.author = e.detail.value
    this.setData({
      bookinfo: val
    })
  },

  //删除书
  delbook() {
    let that = this
    if (this.data.manger == 0) {
      wx.showToast({
        title: '需要管理员',
        image: '/images/fail.png',
        duration: 2000
      })
    } else {
      if (that.data.bookinfo.bookname == "") {
        if (that.data.bookinfo.isbn == "") {
          wx.showToast({
            title: '请输入书名或者ISBN',
            duration: 2000
          })
        } else {
          DB.collection("lchbook").where({
            isbn: that.data.bookinfo.isbn
          }).get({
            success: (res) => {
              let id = res
              if (res.data.length == 0) {
                wx.showToast({
                  title: '未找到该书',
                  image: "/images/fail.png",
                  duration: 2000
                })
              } else {
                wx.showModal({
                  title: "删除!",
                  content: "确认要删除该书吗？",
                  success: (res) => {
                    if (res.confirm) {
                      DB.collection("lchbook").doc(id.data[0]._id).remove({
                        success: (res) => {
                          wx.showToast({
                            title: '删除成功',
                            icon: 'success',
                            duration: 2000
                          })
                        },
                        fail: () => {
                          wx.showToast({
                            title: '数据库失败',
                            image: '/images/fail.png',
                            duration: 2000
                          })
                        }
                      })
                    } else if (res.cancel) {}
                  }
                })
              }
            }
          })
        }
      } else {
        DB.collection("lchbook").where({
          bookname: that.data.bookinfo.bookname
        }).get({
          success: (res) => {
            console.log("2222", res)
            console.log("222", res.data.length)
            let id = res
            if (res.data.length == 0) {
              wx.showToast({
                title: '未找到该书',
                image: '/images/fail.png',
                duration: 2000
              })
            } else {
              wx.showModal({
                title: "删除",
                content: "确认要删除该书吗",
                success: (res) => {
                  if (res.confirm) {
                    DB.collection("lchbook").doc(id.data[0]._id).remove({
                      success: () => {
                        wx.showToast({
                          title: '删除成功',
                          icon: 'success',
                          duration: 2000
                        })
                      },
                      fail: () => {
                        wx.showToast({
                          title: '数据库失败',
                          image: '/images/fail.png',
                          duration: 2000
                        })
                      }
                    })
                  } else {}
                }
              })
            }
          }
        })
      }
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    this.setData({openid: wx.getStorageSync('openid')})

    DB.collection("lchuser").where({
      openid: this.data.openid
    }).get({
      success: (res) => {
        that.setData({
          manger: res.data[0].manger
        })
      }
    })

    DB.collection("lchbook").where({jystate: true }).count({success : function(res){that.setData({outbook : res.total})  }})
    DB.collection("lchbook").where({jystate: false}).count({success : function(res){that.setData({inbook : res.total})  }})
    DB.collection("lchbook").where({hsstate: true}).count({success : function(res){that.setData({hsbook : res.total})  }})



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})